/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.hs.srm.admin.modules.sys.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.Constant;
import com.hs.srm.base.modules.sys.entity.SysMenuEntity;
import com.hs.srm.base.modules.sys.service.SysMenuService;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.common.exception.RRException;
import com.hs.srm.common.utils.R;

/**
 * 系统菜单
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午9:58:15
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {
	
	private static final long serialVersionUID = 6174067932926217750L;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysUserService sysUserService;

	/**
	 * 删除
	 */
	@SysLog("删除菜单")
	@RequestMapping("/delete/{menuId}")
	@RequiresPermissions("sys:menu:delete")
	public R delete(@PathVariable("menuId") long menuId) {
		// if(menuId <= 31){
		// return R.error("系统菜单，不能删除");
		// }

		// 判断是否有子菜单或按钮
		List<SysMenuEntity> menuList = this.sysMenuService.queryListParentId(menuId);
		if(menuList.size() > 0) {
			return R.error("请先删除子菜单或按钮");
		}

		this.sysMenuService.delete(menuId);

		return R.ok();
	}

	/**
	 * 菜单信息
	 */
	@RequestMapping("/info/{menuId}")
	@RequiresPermissions("sys:menu:info")
	public R info(@PathVariable("menuId") Long menuId) {
		SysMenuEntity menu = this.sysMenuService.selectById(menuId);
		return R.ok().put("menu", menu);
	}

	/**
	 * 所有菜单列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions(value = {"sys:menu:list", "sys:menu:fucAuth"}, logical = Logical.OR)
	public List<SysMenuEntity> list(@RequestParam Map<String, Object> params) {
		return this.sysMenuService.query(params);
	}

	/**
	 * 导航菜单
	 */
	@RequestMapping("/nav")
	public R nav() {
		Long currUserId = this.getUserId();
		List<SysMenuEntity> menuList = new ArrayList<>();

		if(currUserId.longValue() == Constant.SUPER_ADMIN) {
			EntityWrapper<SysMenuEntity> wrapper = new EntityWrapper<>();
			wrapper.orderBy("orderNum");
			menuList = this.sysMenuService.selectList(wrapper);
		} else {
			// 用户菜单列表
			List<Long> menuIdList = this.sysUserService.queryAllMenuId(this.getUserId());
			if(!ObjectUtils.isEmpty(menuIdList)) {
				for(Long menuId : menuIdList) {
					SysMenuEntity item = this.sysMenuService.selectById(menuId);
					if(item != null) {
						menuList.add(item);
					}

				}
			}
		}
		if(!ObjectUtils.isEmpty(menuList)) {
			for(SysMenuEntity sysMenuEntity : menuList) {
				SysMenuEntity parentMenuEntity = this.sysMenuService.selectById(sysMenuEntity.getParentId());
				if(parentMenuEntity != null) {
					sysMenuEntity.setParentName(parentMenuEntity.getName());
				}
			}
		}
		return R.ok().put("result", menuList);
	}

	/**
	 * 保存
	 */
	@SysLog("保存菜单")
	@RequestMapping("/save")
	@RequiresPermissions("sys:menu:insert")
	public R save(SysMenuEntity menu) {
		// 数据校验
		this.verifyForm(menu);

		this.sysMenuService.insert(menu);

		return R.ok();
	}

	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@RequestMapping("/select")
	@RequiresPermissions("sys:menu:select")
	public R select() {
		// 查询列表数据
		List<SysMenuEntity> menuList = this.sysMenuService.queryNotButtonList();

		// 添加顶级菜单
		SysMenuEntity root = new SysMenuEntity();
		root.setMenuId(0L);
		root.setName("一级资源");
		root.setParentId(-1L);
		root.setOpen(true);
		menuList.add(root);

		return R.ok().put("result", menuList);
	}

	/**
	 * 跳转至资源编辑页面
	 * @param menuId
	 * @return
	 */
	@RequestMapping("/toEdit/{menuId}")
	public ModelAndView toEdit(@PathVariable("menuId") Long menuId) {
		SysMenuEntity menu = this.sysMenuService.selectById(menuId);

		// 查询上级资源
		if(menu.getParentId() == 0) {
			menu.setParentName("一级资源");
		} else {
			menu.setParentName(this.sysMenuService.selectById(menu.getParentId()).getName());
		}

		ModelAndView modelAndView = new ModelAndView("modules/sys/menu/menu_edit");
		modelAndView.addObject("menu", menu);
		return modelAndView;
	}

	/**
	 * 修改
	 */
	@SysLog("修改菜单")
	@RequestMapping("/update")
	@RequiresPermissions("sys:menu:update")
	public R update(SysMenuEntity menu) {
		// 数据校验
		this.verifyForm(menu);

		this.sysMenuService.updateById(menu);

		return R.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(SysMenuEntity menu) {
		if(StringUtils.isBlank(menu.getName())) {
			throw new RRException("菜单名称不能为空");
		}

		if(menu.getParentId() == null) {
			throw new RRException("上级菜单不能为空");
		}

		// 菜单
		if(menu.getType() == Constant.MenuType.MENU.getValue()) {
			if(StringUtils.isBlank(menu.getUrl())) {
				throw new RRException("菜单URL不能为空");
			}
		}

		// 上级菜单类型
		int parentType = Constant.MenuType.CATALOG.getValue();
		if(menu.getParentId() != 0) {
			SysMenuEntity parentMenu = this.sysMenuService.selectById(menu.getParentId());
			parentType = parentMenu.getType();
		}

		// 目录、菜单
		if(menu.getType() == Constant.MenuType.CATALOG.getValue()
				|| menu.getType() == Constant.MenuType.MENU.getValue()) {
			if(parentType != Constant.MenuType.CATALOG.getValue()) {
				throw new RRException("上级菜单只能为目录类型");
			}
			return;
		}

		// 按钮
		if(menu.getType() == Constant.MenuType.BUTTON.getValue()) {
			if(parentType != Constant.MenuType.MENU.getValue()) {
				throw new RRException("上级菜单只能为菜单类型");
			}
			return;
		}
	}
}
